<template>
  <div class="header_information page-container">
    <!-- 头部 -->
    <el-page-header @back="handleBack">
      <template #content>
        <el-space>
          <h1
            size="large"
            tag="b"
          >ID码管理</h1>
        </el-space>
      </template>
    </el-page-header>
    <!-- 按钮 -->
    <el-row class="el_row_btn">
      <el-col
        :span="24"
        class="content"
      >
        <div class="content_top_btn">
          <span style="flex-shrink: 0; padding-right: 16px;">
            <el-button
              type="primary"
              size="large"
              @click="handleOpenCreateIDModal"
            >
              生成ID码
            </el-button>
          </span>
          <el-space wrap>
            <el-input
              size="large"
              placeholder="请输入ID码"
              v-model="query_data.key"
              clearable
              class="input-default-width"
              style="width:132px"
            ></el-input>
            <el-input
              size="large"
              placeholder="请输入姓名"
              v-model="query_data.studentName"
              clearable
              class="input-default-width"
              style="width:132px"
            ></el-input>
            <el-input
              size="large"
              placeholder="请输入手机号"
              v-model="query_data.phone"
              clearable
              class="input-default-width"
              style="width:132px"
            ></el-input>
            <!-- 赛项选择 -->
            <EventSelect v-model="query_data.rootId" />
            <!-- 组委会选择 -->
            <OrganizingSelect v-model="query_data.agentId" />
            <!-- 机构选择 -->
            <InstitutionSelect
              :disabled="!query_data.agentId"
              :agentId="query_data.agentId"
              v-model="query_data.institutionId"
            />
            <el-select
              placeholder="请选择状态"
              size="large"
              clearable
              style="width:132px"
              v-model="query_data.isUse"
            >
              <el-option
                label="未使用"
                :value="0"
              ></el-option>
              <el-option
                label="已使用"
                :value="1"
              ></el-option>
            </el-select>
            <el-button
              size="large"
              :icon="Search"
              circle
              :loading="loading"
              @click="handleSearch"
            />
          </el-space>
        </div>
      </el-col>
    </el-row>
    <!-- 内容 -->
    <el-row>
      <el-col :span="24">
        <el-table
          empty-text="暂无数据..."
          :data="data"
          border
          style="width: 100%"
          fixed
          v-loading="loading"
        >
          <el-table-column
            prop="key"
            label="ID"
            width="52"
          >
            <template v-slot="{ row }">
              {{ row.keyId }}
            </template>
          </el-table-column>
          <el-table-column
            prop="key"
            label="ID码"
            width="100"
          >
            <template v-slot="{ row }">
              <span
                :title="row.key"
                style="padding-right: 4px;"
              >
                {{ row.key.slice(0,5) }}
              </span>
              <el-icon
                v-if="row.key"
                class="copy-icon"
                @click="handleCopy(row.key)"
              >
                <CopyDocument />
              </el-icon>

            </template>
          </el-table-column>
          <el-table-column
            prop="isUse"
            label="状态"
            width="96px"
            align="center"
          >
            <template v-slot="{ row }">
              <el-tag
                type="success"
                v-if="row.isUse == 0"
              >未使用</el-tag>
              <el-tag
                type="warning"
                v-else
              >已使用</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="生成时间"
            width="200"
          />
          <el-table-column
            prop="studentName"
            label="使用者姓名"
          />
          <el-table-column
            prop="agentName"
            label="组委会名称"
          />
          <el-table-column
            prop="informationName"
            label="机构名称"
          />

          <el-table-column
            prop="phone"
            label="手机号"
          />
          <el-table-column
            prop="entryStatus"
            label="参赛证号"
          >
            <template v-slot="{ row }">
              {{ row.entryNumber }}
            </template>
          </el-table-column>
          <el-table-column
            prop="useTime"
            label="使用时间"
            width="200"
          />

        </el-table>
      </el-col>
    </el-row>
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next, total"
        :total="total"
        @current-change="handlePage"
      />
    </div>
    <!-- id码创建弹窗 -->
    <el-dialog
      v-model="create_id_modal_show"
      title="ID码生成"
      width="640px"
      @closed="() => { handleLoad(true) }"
    >
      <div v-if="create_id_step == 0">
        <el-form
          size="large"
          label-width="72px"
        >
          <el-form-item label="赛项名称">
            <EventSelect
              v-model="create_id_data.rootId"
              class="w-input"
            />
          </el-form-item>
          <el-form-item label="ID码数量">
            <div>
              <el-input-number
                v-model="create_id_data.count"
                :min="1"
                :max="200"
                placeholder="请输入生成数量"
              ></el-input-number>
              <el-text
                size="small"
                tag="p"
              >生成数量最少1个，最多200个</el-text>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button @click="create_id_modal_show = false">取消</el-button>
            <el-button
              type="primary"
              @click="handleCreateID"
              :loading="create_id_loading"
            >生成</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-else-if="create_id_step == 1">
        <div class="create-id-header">
          <el-text>赛项信息</el-text>

        </div>
        <el-scrollbar height="400px">

          <el-table
            style="width:100%"
            :data="id_data"
          >
            <el-table-column
              label="ID码"
              prop="id"
            ></el-table-column>
            <el-table-column
              label="操作"
              width="96px"
            >
              <template #default="scope">
                <el-button
                  size="small"
                  type="info"
                  @click="handleCopy(scope.row.id)"
                >复制</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
        <div class="create-id-btns">
          <el-button
            size="large"
            @click="create_id_step = 0"
          >返回上一步</el-button>
          <el-button
            size="large"
            @click="create_id_modal_show = false"
          >关闭</el-button>
          <el-button
            type="primary"
            size="large"
            @click="handleExportFile"
            title="导出全部ID码"
          >导出全部ID码</el-button>

        </div>

      </div>
    </el-dialog>
  </div>
</template>

<script  setup>
import {
  Search,
  CopyDocument
} from "@element-plus/icons-vue";
import { computed, onMounted, ref } from "vue";
import { ElMessage, ElMessageBox, } from 'element-plus';
import { usePage } from "@/hooks/usePage"
import { getCompetitionListPage, withdrawalRegistration, auditCompetitionStudent } from '@/api/manage/agentmenu/index.js'
import EntrystatusSelect from "@/components/entrystatus-select/index.vue"
import EventSelect from "@/components/event-select/index.vue"
import GroupsSelect from "@/components/groups-select/index.vue"
import InstitutionSelect from "@/components/institution-select/index.vue"
import OrganizingSelect from "@/components/organizing-select/index.vue"
import { useRouter, useRoute } from "vue-router"
import { GetEventInfoByEventIdApi } from "@/api/manage/institution";
import { saveAs } from 'file-saver';
import { writeFile, utils } from 'xlsx'
import { useClipboard } from "@vueuse/core"
import { GenerateKeyApi, GetSecretKeyListPageApi } from "@/api";
import { handleCopyFunc } from "@/utils/copy"
const { copy } = useClipboard();
const router = useRouter();
const route = useRoute();
const query_data_value = ref({
  agent_name: "",
  isUse: "",
  key: "",

})
const {
  total,
  data,
  loading,
  query_data,
  handleLoad,
  handlePage
} = usePage({
  api_fn: GetSecretKeyListPageApi,
  q_data: {
    agentId: "",
    institutionId: "",
    isUse: "",
    key: "",
    rootName: "",
    studentName: '',
    phone: "",
    rootId: ""
  }
})

const handleBack = () => {
  router.back()
}


/**
 * 搜索接口
 */
const handleSearch = () => {
  handleLoad(true)
}

const create_id_modal_show = ref(false)
const create_id_step = ref(0)
const create_id_loading = ref(false)
const create_id_data = ref({
  count: 0,
  rootId: ""
})
/**
 * 打开创建id码弹窗
 */
const handleOpenCreateIDModal = () => {
  create_id_modal_show.value = true;
  create_id_step.value = 0;
  create_id_data.value.count = 1;
  create_id_data.value.rootId = "";
}
const id_data = ref([])
/**
 * 生成码
 */
const handleCreateID = async () => {
  //   create_id_step.value = 1;
  if (!create_id_data.value.rootId) {
    ElMessage.error("请选择赛项！");
    return;
  }
  create_id_loading.value = true;
  create_id_step.value = 1;
  create_id_loading.value = false;
  let res = await GenerateKeyApi(create_id_data.value);
  if (!res.success) {
    ElMessage.error(res.message);
  } else {
    ElMessage.success(res.message);
    id_data.value = res.entityList.map((item) => {
      return {
        id: item
      }
    });
  }
}



const handleExportFile = () => {
  //   let text_data = [
  //     `ID码总数：${create_id_data.value.count}\r\n`,
  //     `ID码如下：\r\n`,
  //   ];
  //   let arr = id_data.value.map((item) => {
  //     return item.id + "\r\n"
  //   })
  //   text_data.push(...arr)
  //   let blob = new Blob(text_data, { type: "text/plain;charset=utf-8" });
  //   ElMessage.success("正在导出");
  //   saveAs(blob, "ID码.txt");

  let data = id_data.value.map((item) => {
    return {
      "ID码": item.id
    }
  })
  // 新建空workbook，然后加入worksheet
  const ws = utils.json_to_sheet(data)
  // 设置每列的列宽，10代表10个字符，注意中文占2个字符
  ws['!cols'] = [
    { wch: 52 },
  ]
  // 新建book
  const wb = utils.book_new()
  // 生成xlsx文件(book,sheet数据,sheet命名)
  utils.book_append_sheet(wb, ws, 'ID码')
  // 写文件(book,xlsx文件名称)
  let blob = writeFile(wb, 'ID码.xlsx')
  ElMessage.success("正在导出");
  saveAs(blob, 'ID码.xlsx');

}

/**
 * 复制
 */
const handleCopy = (content) => {
  handleCopyFunc(content);
  ElMessage.success("复制成功：" + content);

}
onMounted(() => {
  handleLoad(true)
})
</script>

<style lang="scss" scoped>
.header_information {
  padding: 20px;

  .header_name {
    margin-left: 10px;
    margin-right: 10px;

    .header_text {
      margin-left: -10px;
      margin-right: -10px;
    }

    h1 {
      font-size: 28px;
    }

    // 线
    .header_line {
      display: block;
      height: 1px;
      width: 100%;
      margin: 24px 0 20px 0;
      background-color: #8473f717;
    }
  }

  //   内容
  .el_row_btn {
    margin-bottom: 20px;

    .content {
      .content_top_btn {
        display: flex;
        justify-content: space-between;
        padding-top: 24px;

        .top_search_inp {
          width: 300px;
          height: 40px;
          margin-right: 5px;
        }

        .top_search_btn {
          width: 110px;
          margin-right: 5px;
        }
      }
    }
  }

  .el-radio {
    margin: 0 0 0 5px;
  }

  :deep(.el-table)__cell {
    padding: 12px 0 !important;
  }

  // 分页
  .pagination {
    margin-top: 30px;
    margin-bottom: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 50px;
  }
}

.create-id-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
}

.create-id-btns {
  padding-top: 16px;
  display: flex;
  justify-content: center;
}

.copy-icon {
  cursor: pointer;
}

.w-input {
  width: 100%;
  :deep(.el-input) {
    width: 100%;
  }
  .el-input-number {
    width: 100%;
  }
}
</style>